/* This DOS utility converts an Intel Hex format file into a binary file.  *
 * Useful, for example, when using crunchers to compress data which is     *
 * already in .asm form and can be assembled, linked, and the resulting    *
 * .HEX file can be converted to binary and crunched. The DB/DW utilities  *
 * can then be used to put the crunched binary file back into .asm form.   *
 *					written by Paul Hutchinson							    */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "dos.h"


FILE	*infile, *outfile;  /* input & output files */

int ch;



void Hextobin(void)
{
	int	length,byte;

	while (1)
		{
		if	((ch = getc(infile)) == EOF)
			break;

		if	((ch = getc(infile)) != EOF)
			{
			if ((ch > 47) && (ch < 58))
				ch -= 48;
			else
			if ((ch > 64) && (ch < 71))
				ch -= 55;
			else
			ch = 0;
			}
		else
			break;

		length = 16 * ch;

		if	((ch = getc(infile)) !=EOF)
			{
			if ((ch > 47) && (ch < 58))
				ch -= 48;
			else
			if ((ch > 64) && (ch < 71))
				ch -= 55;
			else
			ch = 0;
			}
		else
			break;

		length += ch;

		if	((ch = getc(infile)) == EOF)
			break;
		if	((ch = getc(infile)) == EOF)
			break;
		if	((ch = getc(infile)) == EOF)
			break;
		if	((ch = getc(infile)) == EOF)
			break;
		if	((ch = getc(infile)) == EOF)
			break;
		if	((ch = getc(infile)) == EOF)
			break;

		while (length-- > 0)
			{
			if	((ch = getc(infile)) != EOF)
				{
				if ((ch > 47) && (ch < 58))
					ch -= 48;
				else
				if ((ch > 64) && (ch < 71))
					ch -= 55;
				else
				ch = 0;
				}
			else
				break;

			byte = 16 * ch;

			if	((ch = getc(infile)) !=EOF)
				{
				if ((ch > 47) && (ch < 58))
					ch -= 48;
				else
				if ((ch > 64) && (ch < 71))
					ch -= 55;
				else
				ch = 0;
				}
			else
				break;

			byte += ch;
			putc(byte,outfile);
			}
		if	((ch = getc(infile)) == EOF)
			break;
		if	((ch = getc(infile)) == EOF)
			break;
		if	((ch = getc(infile)) == EOF)
			break;

		}
}

int main(int argc, char *argv[])
{
	if (argc != 3)
	{
		printf("HEXTOBIN: convert file\n");
		printf("Usage: HEXTOBIN infile outfile\n");
		return EXIT_FAILURE;
	}
	if ((infile = fopen(argv[1], "r")) == NULL)
	{
		fprintf(stderr, "HEXTOBIN: Unable to open file: %s\n", argv[1]);
		return EXIT_FAILURE;
	}

	if ((outfile = fopen(argv[2], "wb")) == NULL)
	{
		fprintf(stderr, "HEXTOBIN: Unable to create file: %s\n", argv[2]);
		return EXIT_FAILURE;
	}

	Hextobin();

	fclose(infile);
	fclose(outfile);

	return EXIT_SUCCESS;
}


